const app = getApp()
import { save, update, del } from '../../../../api/address'
const util = require('../../../../utils/util.js')
Page({
  data: {
    array: ['有电梯', '1楼', '2楼', '3楼', '4楼', '5楼', '6楼', '7楼', '8楼', '9楼'],
    title: "",
    type: "",
    isDefault: true, //是否是默认地址
    id: "",
    phone: "",
    level: 0,
    latitude: "",
    longitude: "",
    consignee: "",
    building: "",
    areaName: "",
    address: "",
    addressDetail: "",
    roomNumber: "",
    recognitionContet: "",
    pasterecognition: '粘贴识别',
    SCOPE_TYPE: app.SCOPE_TYPE,
    areaId: '',
    submitFlag: false
  },
  onLoad: function (e) {
    let _this = this
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('sendAddressDetail', function (data) {
      if (data.type == "add") {
        _this.setData({
          type: data.type,
          title: "添加收货地址"
        })
      } else if (data.type == "edit") {
        _this.setData({
          title: "编辑收货地址",
          type: data.type,
          id: data.data.id,
          isDefault: data.data.isDefault, //是否是默认地址
          phone: data.data.phone,
          latitude: data.data.lat,
          longitude: data.data.lng,
          level: data.data.level,
          consignee: data.data.consignee,
          building: data.data.building,
          areaName: data.data.areaName,
          address: data.data.address,
          roomNumber: data.data.roomNumber,
          memberId: data.data.memberId,
          addressDetail: data.data.addressDetail,
        })
      }
    })
  },
  onShow: function () {
    app.event.on("onCartChange", this.onCartChange)
  },
  addr_change(e) {
    let building = ""
    e.detail.value.forEach(item => {
      building = building + item
    })
    e.detail.code[2]
    this.setData({
      areaId: e.detail.code[2],
      // latitude: res.latitude,
      // longitude: res.longitude,
      building: building,
      // addressDetail: res.address,
      // areaName: res.address.substring(0, res.address.indexOf("区")+1),
      // address: res.address,
    })
  },
  onCartChange(data) {
    let building
    if (data.address.indexOf(data.adName) == 0) {
      building = data.address + "(" + data.name + ")"
    } else {
      building = data.adName + data.address + "(" + data.name + ")"
    }
    let _this = this
    let location = data.location.split(',')
    this.setData({
      latitude: location[1],
      longitude: location[0],
      building: building,
      areaName: data.adName,
      address: data.address,
      addressDetail: data.address + "(" + data.name + ")"
    })
  },
  pasteClick() {
    if (this.data.pasterecognition == '粘贴识别') {
      wx.getClipboardData({
        success: res => {
          this.data.recognitionContet = res.data

          this.setData({
            recognitionContet: this.data.recognitionContet
          })
          let nameAndaddress = this.data.recognitionContet
          this.autoDiscern(nameAndaddress)
        }
      })
    } else if (this.data.pasterecognition == '识别') {
      this.autoDiscern(this.data.recognitionContet)
    }
  },
  recognitionClick(data) {
    this.data.recognitionContet = data.detail.value
    this.setData({
      recognitionContet: this.data.recognitionContet,
      pasterecognition: this.data.pasterecognition,
    })

    if (this.data.recognitionContet != "") {
      this.data.pasterecognition = '识别'
      this.setData({
        pasterecognition: this.data.pasterecognition,
      })
    } else {
      this.data.pasterecognition = '粘贴识别'
      this.setData({
        pasterecognition: this.data.pasterecognition,
      })
    }
  },
  //自动识别事件
  autoDiscern(nameAndaddress) {
    var province = ["广东", "北京", "浙江", "福建", "湖北", "上海", "江苏", "天津", "河北", "山西", "内蒙古", "辽宁", "吉林", "黑龙江", "安徽", "江西", "山东", "河南", "湖南", "广西", "海南", "重庆", "四川", "贵州", "云南", "西藏", "陕西", "甘肃", "青海", "宁夏", "新疆", "台湾", "香港", "澳门"];
    var familyName = ['赵', '钱', '孙', '李', '周', '吴', '郑', '王', '冯', '陈', '楮', '卫', '蒋', '沈', '韩', '杨', '朱', '秦', '尤', '许', '何', '吕', '施', '张', '孔', '曹', '严', '华', '金', '魏', '陶', '姜', '戚', '谢', '邹', '喻', '柏', '水', '窦', '章', '云', '苏', '潘', '葛', '奚', '范', '彭', '郎', '鲁', '韦', '昌', '马', '苗', '凤', '花', '方', '俞', '任', '袁', '柳', '酆', '鲍', '史', '唐', '费', '廉', '岑', '薛', '雷', '贺', '倪', '汤', '滕', '殷', '罗', '毕', '郝', '邬', '安', '常', '乐', '于', '时', '傅', '皮', '卞', '齐', '康', '伍', '余', '元', '卜', '顾', '孟', '平', '黄', '和', '穆', '萧', '尹', '姚', '邵', '湛', '汪', '祁', '毛', '禹', '狄', '米', '贝', '明', '臧', '计', '伏', '成', '戴', '谈', '宋', '茅', '庞', '熊', '纪', '舒', '屈', '项', '祝', '董', '梁', '杜', '阮', '蓝', '闽', '席', '季', '麻', '强', '贾', '路', '娄', '危', '江', '童', '颜', '郭', '梅', '盛', '林', '刁', '锺', '徐', '丘', '骆', '高', '夏', '蔡', '田', '樊', '胡', '凌', '霍', '虞', '万', '支', '柯', '昝', '管', '卢', '莫', '经', '房', '裘', '缪', '干', '解', '应', '宗', '丁', '宣', '贲', '邓', '郁', '单', '杭', '洪', '包', '诸', '左', '石', '崔', '吉', '钮', '龚', '程', '嵇', '邢', '滑', '裴', '陆', '荣', '翁', '荀', '羊', '於', '惠', '甄', '麹', '家', '封', '芮', '羿', '储', '靳', '汲', '邴', '糜', '松', '井', '段', '富', '巫', '乌', '焦', '巴', '弓', '牧', '隗', '山', '谷', '车', '侯', '宓', '蓬', '全', '郗', '班', '仰', '秋', '仲', '伊', '宫', '宁', '仇', '栾', '暴', '甘', '斜', '厉', '戎', '祖', '武', '符', '刘', '景', '詹', '束', '龙', '叶', '幸', '司', '韶', '郜', '黎', '蓟', '薄', '印', '宿', '白', '怀', '蒲', '邰', '从', '鄂', '索', '咸', '籍', '赖', '卓', '蔺', '屠', '蒙', '池', '乔', '阴', '郁', '胥', '能', '苍', '双', '闻', '莘', '党', '翟', '谭', '贡', '劳', '逄', '姬', '申', '扶', '堵', '冉', '宰', '郦', '雍', '郤', '璩', '桑', '桂', '濮', '牛', '寿', '通', '边', '扈', '燕', '冀', '郏', '浦', '尚', '农', '温', '别', '庄', '晏', '柴', '瞿', '阎', '充', '慕', '连', '茹', '习', '宦', '艾', '鱼', '容', '向', '古', '易', '慎', '戈', '廖', '庾', '终', '暨', '居', '衡', '步', '都', '耿', '满', '弘', '匡', '国', '文', '寇', '广', '禄', '阙', '东', '欧', '殳', '沃', '利', '蔚', '越', '夔', '隆', '师', '巩', '厍', '聂', '晁', '勾', '敖', '融', '冷', '訾', '辛', '阚', '那', '简', '饶', '空', '曾', '毋', '沙', '乜', '养', '鞠', '须', '丰', '巢', '关', '蒯', '相', '查', '后', '荆', '红', '游', '竺', '权', '逑', '盖', '益', '桓', '公', '万俟', '司马', '上官', '欧阳', '夏侯', '诸葛', '闻人', '东方', '赫连', '皇甫', '尉迟', '公羊', '澹台', '公冶', '宗政', '濮阳', '淳于', '单于', '太叔', '申屠', '公孙', '仲孙', '轩辕', '令狐', '锺离', '宇文', '长孙', '慕容', '鲜于', '闾丘', '司徒', '司空', '丌官', '司寇', '仉', '督', '子车', '颛孙', '端木', '巫马', '公西', '漆雕', '乐正', '壤驷', '公良', '拓拔', '夹谷', '宰父', '谷梁', '晋', '楚', '阎', '法', '汝', '鄢', '涂', '钦', '段干', '百里', '东郭', '南门', '呼延', '归', '海', '羊舌', '微生', '岳', '帅', '缑', '亢', '况', '后', '有', '琴', '梁丘', '左丘', '东门', '西门', '商', '牟', '佘', '佴', '伯', '赏', '南宫', '墨', '哈', '谯', '笪', '年', '爱', '阳', '佟', '第五', '言', '福'];
    var other = [];
    var nameAndaddress = nameAndaddress.replace(/\s*/g, "").replace(/，/, ',').split(',').map(item => item.trim()).join('');
    var name = nameAndaddress.replace(/\s*/g, "").replace(/，/, ',').split(',').map(item => item.trim()).join('');
    var address = nameAndaddress.replace(/\s*/g, "").replace(/，/, ',').split(',').map(item => item.trim()).join('');
    let phone = name.match(/([1][3-9]\d{9}(-[0-9]{4})?)/g);
    if (phone == null) {
      phone = name.match(/(86-[1][0-9]{10}) | (86[1][0-9]{10})|([1][0-9]{10})/g);
    }
    if (phone != null && phone != '') {
      phone.forEach(item => {
        item = item.toString().replace(new RegExp(",", "g"), '').replace(new RegExp(" ", "g"), '');
      })
      other = name.split(phone[0]);
      if (other[0] == '') {//地址在后面
        nameAndaddress = other[1].replace(new RegExp(" ", "g"), ''); //去掉手机号剩下的
        for (var i = 0; i < province.length; i++) {
          if (nameAndaddress.indexOf(province[i]) == 0) {//第一位是省份
            for (var i = 0; i < familyName.length; i++) {
              if (nameAndaddress.lastIndexOf(familyName[i]) != -1) {//有姓氏
                var index = nameAndaddress.lastIndexOf(familyName[i]); //截取字符串
                address = nameAndaddress.substring(0, index);//前面为地址 后面为姓氏
                name = nameAndaddress.substring(index, nameAndaddress.length);
                break;
              } else {//没有姓氏

              }
            }
            break;
          } else if (nameAndaddress.indexOf(province[i]) == -1) {//没有省份信息

          } else {
            var index = nameAndaddress.indexOf(province[i]);//不在第一位  //截取字符串 //前面为姓名  后面为地址
            name = nameAndaddress.substring(0, index);
            address = nameAndaddress.substring(index, nameAndaddress.length);
          }
        }
      } else if (other[1] == '') {   //地址在前面
        nameAndaddress = other[0].replace(new RegExp(" ", "g"), '');  //去掉手机号剩下的
        for (var i = 0; i < province.length; i++) {

          if (nameAndaddress.indexOf(province[i]) == 0) {//第一位是省份
            for (var i = 0; i < familyName.length; i++) {
              if (nameAndaddress.lastIndexOf(familyName[i]) != -1) {//有姓氏
                var index = nameAndaddress.lastIndexOf(familyName[i]);  //截取字符串
                address = nameAndaddress.substring(0, index); //前面为地址 后面为姓氏
                break;
              }
              else {//没有姓氏

              }
            }
            break;
          } else if (nameAndaddress.indexOf(province[i]) == -1) {//没有省份信息

          } else {
            var index = nameAndaddress.indexOf(province[i]);  //不在第一位
            name = nameAndaddress.substring(0, index);  //截取字符串
            address = nameAndaddress.substring(index, nameAndaddress.length);   //前面为姓名  后面为地址
          }
        }
      } else {
        if (other[0].length > other[1].length) {
          address = other[0];
          name = other[1];
        } else if (other[0].length < other[1].length) {
          address = other[1];
          name = other[0];
        }
      }
    } else {
      wx.showToast({  //没有正确的手机号码
        title: '没有正确的手机号码',
      })
    }
    if (name == '' || phone == '' || phone == name || name.length > 6) {
      wx.showToast({
        title: '识别异常！备注:姓名、电话、在前。',
        icon: 'none'
      })
    } else {
      let building = this.getArea(address)
      this.data.consignee = name
      this.data.phone = phone[0]
      this.data.areaName = this.data.building = building.Province + building.City + building.Country
      this.data.roomNumber = address.replace(this.data.building, "")
      this.data.lat = 0
      this.data.lng = 0
      this.setData({
        consignee: name,
        phone: phone[0],
        building: this.data.building,
        lat: this.data.lat,
        lng: this.data.lng,
        roomNumber: this.data.roomNumber,
        areaName: this.data.areaName
      })
    }
  },
  //省市区截取
  getArea: function (str) {
    let area = {}
    let index11 = 0
    let index1 = str.indexOf("省")
    if (index1 == -1) {
      index11 = str.indexOf("自治区")
      if (index11 != -1) {
        area.Province = str.substring(0, index11 + 3)
      } else {
        area.Province = str.substring(0, 0)
      }
    } else {
      area.Province = str.substring(0, index1 + 1)
    }

    let index2 = str.indexOf("市")
    if (index11 == -1) {
      area.City = str.substring(index11 + 1, index2 + 1)
    } else {
      if (index11 == 0) {
        area.City = str.substring(index1 + 1, index2 + 1)
      } else {
        area.City = str.substring(index11 + 3, index2 + 1)
      }
    }
    let newStr = str.replace(/小区/g, "").replace(/社区/g, "");
    let index3 = newStr.lastIndexOf("区")
    if (index3 == -1) {
      if (str.indexOf("镇")) {
        index3 = str.indexOf("镇")
        area.Country = str.substring(index2 + 1, index3 + 1)
      } else {
        index3 = str.indexOf("县")
        area.Country = str.substring(index2 + 1, index3 + 1)
      }
    } else {
      area.Country = str.substring(index2 + 1, index3 + 1)
    }
    return area;
  },
  //跳转到区域选择页面
  toSelectArea(e) {
    wx.chooseLocation({
      success: res => {
        if (res.city != null) {
          wx.showToast({
            title: '请选择详情地址',
            icon: 'none', //如果要纯文本，不要icon，将值设为'none'
            duration: 2000
          })
          return false
        }
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          building: res.name + "(" + res.address + ")",
          addressDetail: res.address,
          areaName: res.address.substring(0, res.address.indexOf("区") + 1),
          address: res.address,
        })
      },
      fail: err => {
        wx.showToast({
          title: err,
          icon: 'none'
        });
      }
    })
  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      level: e.detail.value
    })
  },
  //默认地址的滑动按钮
  switchChange(e) {
    this.setData({
      isDefault: e.detail.value
    })
  },
  //表单提交事件
  submit() {
    if (util.isNull(this.data.consignee)) {
      wx.showToast({
        title: '联系人不能为空',
        icon: 'none', //如果要纯文本，不要icon，将值设为'none'
        duration: 2000
      })
    } else if (util.isNull(this.data.phone)) {
      wx.showToast({
        title: '联系电话不能为空',
        icon: 'none', //如果要纯文本，不要icon，将值设为'none'
        duration: 2000
      })
    } else if (util.isNull(this.data.building)) {
      wx.showToast({
        title: '请点选收货地址',
        icon: 'none', //如果要纯文本，不要icon，将值设为'none'
        duration: 2000
      })
    } else if (util.isNull(this.data.roomNumber)) {
      wx.showToast({
        title: '楼号、小区、门牌号不能为空',
        icon: 'none', //如果要纯文本，不要icon，将值设为'none'
        duration: 2000
      })
    } else {
      if (!this.data.submitFlag) {
        this.data.submitFlag = true
        let data = {}
        data.consignee = this.data.consignee
        data.phone = this.data.phone
        data.address = this.data.building + ' ' + this.data.roomNumber
        if ((this.data.building + ' ' + this.data.roomNumber).substring(0, (this.data.building + ' ' + this.data.roomNumber).indexOf("区") + 1) != "") {
          data.areaName = (this.data.building + ' ' + this.data.roomNumber).substring(0, (this.data.building + ' ' + this.data.roomNumber).indexOf("区") + 1)
        } else
          if ((this.data.building + ' ' + this.data.roomNumber).substring(0, (this.data.building + ' ' + this.data.roomNumber).indexOf("县") + 1) != "") {
            data.areaName = (this.data.building + ' ' + this.data.roomNumber).substring(0, (this.data.building + ' ' + this.data.roomNumber).indexOf("县") + 1)
          } else
            if (data.areaName == "" || data.areaName == null) {
              data.areaName = this.data.building
            }
        data.building = this.data.building
        data.level = this.data.level
        data.isDefault = this.data.isDefault
        data.roomNumber = this.data.roomNumber
        data.memberId = this.data.memberId
        data.lat = this.data.latitude
        data.lng = this.data.longitude
        data.lng = this.data.longitude
        data.areaId = this.data.areaId
        if (this.data.type == "add") {
          save(data).then(res => {
            if (res.type == 'success') {
              wx.navigateBack({
                delta: 1,
              })
            }
          }).catch(error => {
            this.data.submitFlag = false
            wx.showToast({
              title: error.content,
              icon: 'none', //如果要纯文本，不要icon，将值设为'none'
              duration: 2000
            })
          })
        } else if (this.data.type == "edit") {
          data.id = this.data.id
          update(data).then(res => {
            if (res.type == 'success') {
              wx.navigateBack({
                delta: 1,
              })
            }
          }
          ).catch(error => {
            this.data.submitFlag = false
            wx.showToast({
              title: error.content,
              icon: 'none', //如果要纯文本，不要icon，将值设为'none'
              duration: 2000
            })
          })
        }
      }
    }
  },
  //表单重置事件
  formReset(e) {
    this.setData({
      area: ''
    })
  },
  //地址删除的事件
  del() {
    del(this.data.id).then(
      res => {
        console.log("删除地址res--" + JSON.stringify(res))
        if (res.type == 'success') {
          wx.navigateBack({
            delta: 1,
          })
        }
      }
    ).catch(error => {
      wx.showToast({
        title: error.content,
        icon: 'none', //如果要纯文本，不要icon，将值设为'none'
        duration: 2000
      })
    })
  },
  nameClick(data) {
    this.data.consignee = data.detail.value
    this.setData({
      consignee: this.data.consignee
    })
  },
  selectAreaClick(data) {
    this.data.building = data.detail.value
    this.setData({
      building: this.data.building
    })
  },
  phoneClick(data) {
    this.data.phone = data.detail.value
    this.setData({
      phone: this.data.phone
    })
  },
  roomClick(data) {
    this.data.roomNumber = data.detail.value
    this.setData({
      roomNumber: this.data.roomNumber
    })
  }
})
